<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\model\Goods;
use app\common\model\GoodsCategory as GoodsCategoryModel;
use app\common\model\GoodsSpec;

class Index extends Base
{
    /**
     * 获取网站配置
     */
    public function siteConfig()
    {
        $data = [
            'site_name'              => conf('site_name'),
            'site_subtitle'          => conf('site_subtitle'),
            'site_logo'              => conf('site_logo'),
            'site_domain'            => conf('site_domain'),
            'site_info_copyright'    => conf('site_info_copyright'),
            'site_info_icp'          => conf('site_info_icp'),
            'merchant_logo'          => conf('merchant_logo'),
            'merchant_logo_sm'       => conf('merchant_logo_sm'),
            'site_currency_symbol'   => conf('site_currency_symbol'),
            'site_currency_name'     => conf('site_currency_name'),
            'site_currency_decimals' => conf('site_currency_decimals'),
        ];
        $this->success("获取成功", $data);
    }

    /**
     * 获取语言
     */
    private function allowedLanguages(): array
    {
        $dirs = glob(base_path() . '/resource/translations/*', GLOB_ONLYDIR);
        return array_map('basename', $dirs);   // ['zh_CN','en',...]
    }

    public function setLang()
    {
        $lang = inputs('lang');
        // en_US 转 en
        $lang  = str_replace('en_US', 'en', $lang);
        $allow = $this->allowedLanguages();

        if (in_array($lang, $allow)) {
            session(['lang' => $lang]);

            // 如果是POST请求（admin后台），返回JSON响应
            if (request()->isPost()) {
                $this->success('', ['lang' => $lang]);
            }

            // GET请求（前台）保持跳转行为
            return redirect(request()->header('referer') ?? '/');
        } else {
            // 语言不在允许列表中
            if (request()->isPost()) {
                $this->error('');
            }

            return redirect(request()->header('referer') ?? '/');
        }
    }

    /**
     * 异常页面
     */
    public function exception()
    {
        $msg = inputs('msg');
        return view('exception', [
            'msg' => $msg
        ]);
    }

    /**
     * 商品分类
     */
    public function getCategory()
    {
        $list = GoodsCategoryModel::getCategoryList();
        $this->success('获取成功', $list);
    }

    /**
     * 获取分类及其所有子分类ID
     * @param int $cateId 分类ID
     * @return array 包含当前分类及所有子分类的ID数组
     */
    private function getAllCateIds($cateId)
    {
        $ids = [$cateId]; // 初始包含当前分类ID

        // 查找直接子分类
        $children = GoodsCategoryModel::where([
            'status' => 1,
            'pid'    => $cateId
        ])->column('id');

        // 递归获取每个子分类的子分类
        foreach ($children as $childId) {
            $ids = array_merge($ids, $this->getAllCateIds($childId));
        }

        return $ids;
    }

    /**
     * 按分类查找商品 带分页
     * 包含指定分类及其所有子分类的商品
     */
    public function goodsListByCate()
    {
        $cate_id         = inputs('id');
        $where           = [];
        $where['status'] = 1;

        // 获取规格筛选条件
        $spec_filters = inputs('spec_filters/a', []);

        // 基础查询对象
        $query = Goods::where($where);

        if ($cate_id) {
            // 获取当前分类及所有子分类的ID
            $cateIds = $this->getAllCateIds($cate_id);
            $query->whereIn('cate_id', $cateIds);
        }

        // 如果有规格筛选条件，添加联合查询
        if (!empty($spec_filters)) {
            // 添加规格关联表的联合查询
            $query->alias('g')
                ->join('goods_spec_relation r', 'g.id = r.goods_id');

            // 处理每个筛选条件
            foreach ($spec_filters as $field => $value) {
                if (empty($value)) {
                    continue; // 跳过空值
                }

                // 统一使用LIKE查询处理所有文本字段  这样可以支持多值字段
                $query->where("JSON_EXTRACT(r.spec_value, '$." . $field . "') LIKE '%" . $value . "%'");
            }

            // 排序并分页 只要商品表
            $goods = $query->order('g.sort desc, g.id desc')->field('g.*')->paginate($this->limit);
        } else {
            $goods = Goods::where($where)->whereIn('cate_id', $cateIds)->order('sort desc, id desc')->paginate($this->limit);
        }
        $this->success('获取成功', ['list' => $goods->items(), 'total' => $goods->total()]);
    }

    /**
     * 商品详情
     */
    public function goodsDetail()
    {
        $id          = inputs('id');
        $goods       = Goods::where([
            'status' => 1,
            'id'     => $id
        ])->find();
        $goods->cate = $goods->category;
        $this->success('获取成功', $goods);
    }


    /**
     * 搜索商品
     */
    public function searchGoods()
    {
        $keyword = inputs('keyword');
        $goods   = Goods::where('status', 1)->where('name', 'like', '%' . $keyword . '%')->order('sort desc, id desc')->paginate($this->limit);
        $this->success('获取成功', ['list' => $goods->items(), 'total' => $goods->total()]);
    }

    /**
     * 获取分类的规格筛选字段
     * 只返回可用于筛选的字段（select类型且有选项的字段）
     * 同时返回分类中定义的额外检索条件
     */
    public function getSpecFilter()
    {
        $cate_id = inputs('cate_id');

        // 获取分类信息
        $category = GoodsCategoryModel::where('id', $cate_id)->where('status', 1)->find();

        if (!$category) {
            $this->error('分类不存在');
        }

        $result = [];

        // 处理规格筛选字段
        if ($category->is_spec_filter && $category->spec_id) {
            // 获取规格信息
            $spec = GoodsSpec::where('id', $category->spec_id)->where('status', 1)->find();
            if ($spec) {
                // 提取可用于筛选的字段（select类型）
                // 使用toArray()方法获取包括JSON字段在内的所有字段
                $spec_data = $spec->toArray();

                // 直接从数组中获取rule_value字段
                $rule_value = $spec_data['rule_value'] ?? [];

                if (is_array($rule_value)) {
                    foreach ($rule_value as $field) {
                        if (isset($field['type']) && $field['type'] == 'select' && !empty($field['detail'])) {
                            $result[] = [
                                'spec_id'     => $spec->getData('id'),
                                'spec_name'   => $spec->getData('name'),
                                'field_name'  => $field['value'],
                                'field_label' => $field['label'],
                                'options'     => $field['detail'],
                                'filter_type' => 'spec', // 标记为规格筛选
                            ];
                        }
                    }
                }
            }
        }

        // 处理额外的检索条件
        $search_filters = $category->search_filters;
        if (!empty($search_filters) && is_array($search_filters)) {
            foreach ($search_filters as $filter) {
                if (!empty($filter['title']) && !empty($filter['value']) && !empty($filter['bind_search'])) {
                    // 将逗号分隔的值转换为数组
                    $options = explode(',', $filter['value']);
                    $options = array_map('trim', $options); // 去除可能的空格

                    $result[] = [
                        'field_name'  => $filter['bind_search'],
                        'field_label' => $filter['title'],
                        'options'     => $options,
                        'filter_type' => 'custom', // 标记为自定义筛选
                    ];
                }
            }
        }

        $this->success('获取成功', $result);
    }


    /**
     * 获取商品推荐
     */
    public function getRecommendGoods()
    {
        $goods = Goods::where([
            'status' => 1,
        ])->order('sort desc, id desc')->limit(10)->select();
        $this->success('获取成功', $goods);
    }

    /**
     * 跳转到应用市场登录地址
     */
    public function goMarketLoginPage()
    {
        $market_url = config('site.marketplace.main_api_url');
        return redirect($market_url . '/register');
    }
}
